package com.realtyManage.springboot.Service.impl;

import com.realtyManage.springboot.Config.MyLog;
import com.realtyManage.springboot.Dao.*;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Vo.RegEntity;
import com.realtyManage.springboot.Model.Vo.UserTaskEntity;
import com.realtyManage.springboot.Service.ICustomerRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CouponServiceImpl {
    @Autowired
    private UserTaskRepository userTaskRepository;

    @Autowired
    private CustomerLevelTimeRepository customerLevelTimeRepository;

    @Autowired
    private ForwardRepository forwardRepository;

    @Autowired
    private ICustomerRegistrationService customerRegistrationService;

    @Autowired
    private ConferenceContentRepository conferenceContentRepository;

    @Autowired
    private CouponRepository couponRepository;


    public UserTask findById(Integer userId) {
        return userTaskRepository.findById(userId).orElse(null);
    }


    //@MyLog(value = "新增优惠劵")
    public int addCoupon(Coupon coupon) {
        Integer a = 0;
        if (couponRepository.saveAndFlush(coupon).getId() > 0){
            a = 1;
        }
        return a;
    }

    public int update(Coupon coupon) {
        return couponRepository.updateCoupon(coupon);
    }

    public int distributeCoupon(String saleId,Integer id){
        return couponRepository.distributeCoupon(saleId,id);
    }

    @MyLog(value = "查询任务列表")
    public Page<UserTask> findPagedByWhereClause(UserTaskEntity userTaskEntity) {
        Integer pageNumber = userTaskEntity.getPageNumber()-1;
        Integer pageSize = userTaskEntity.getPageSize();
        //排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if(userTaskEntity.getSort() != null){
            if (userTaskEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, userTaskEntity.getSortField());
            } else if(userTaskEntity.getSort().equals("ASC")){
                sort = new Sort(Sort.Direction.ASC, userTaskEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber,pageSize,sort);

        //动态查询条件
        Specification<UserTask> specification = (Specification<UserTask>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (userTaskEntity.getDistributionUserId()!=null) {
                // 根据角色查询
                Predicate p1 = criteriaBuilder.equal(root.get("distributionUserId"),userTaskEntity.getDistributionUserId());
                list.add(p1);
            }
            if (userTaskEntity.getType()!=null) {
                // 根据类型查询
                Predicate p2 = criteriaBuilder.equal(root.get("taskType"),userTaskEntity.getType() );
                list.add(p2);
            }
            Predicate p3 = criteriaBuilder.equal(root.get("isShow"),0 );
            list.add(p3);

            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return userTaskRepository.findAll(specification, pageable);
    }

    @MyLog(value = "删除任务")
    public UserTask deleteTask(String ids) {
        return null;
    }


    public CustomerLevelTime insertLevelTime(CustomerLevelTime customerLevelTime) {
        return customerLevelTimeRepository.saveAndFlush(customerLevelTime);
    }

    public int deleteLevelTime(String ids) {
        return customerLevelTimeRepository.deleteLevelTime(ids);
    }

    @MyLog(value = "查询客户等级时间设置列表")
    public Page<CustomerLevelTime> findPagedByWhereClause(RegEntity regEntity) {
        Integer pageNumber = regEntity.getPageNumber()-1;
        Integer pageSize = regEntity.getPageSize();
        //排序条件
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        if(regEntity.getSort() != null){
            if (regEntity.getSort().equals("DESC")) {
                sort = new Sort(Sort.Direction.DESC, regEntity.getSortField());
            } else if(regEntity.getSort().equals("ASC")){
                sort = new Sort(Sort.Direction.ASC, regEntity.getSortField());
            }
        }
        Pageable pageable = PageRequest.of(pageNumber,pageSize,sort);

        //动态查询条件
        Specification<CustomerLevelTime> specification = (Specification<CustomerLevelTime>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return customerLevelTimeRepository.findAll(specification, pageable);
    }

    public List<ConferenceContent> myConferenceContent(Integer userId,String time) {
        //动态查询条件
        Specification<ConferenceContent> specification = (Specification<ConferenceContent>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (userId != null) {
                // 根据角色查询
                Predicate p1 = criteriaBuilder.equal(root.get("userId"),userId);
                list.add(p1);
            }
            if (userId != null) {
                // 根据角色时间查询
                Predicate p2 = criteriaBuilder.like(root.get("startTime"),"%"+time+"%");
                list.add(p2);
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        return conferenceContentRepository.findAll(specification);
    }


    public List<UserTask> queryMyTask(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return userTaskRepository.queryMyTask(userId,sdf.format(new Date()));
    }


    public List<Coupon> findCoupon(String userId,String time) {
        return couponRepository.findCoupon(userId,time);
    }

    public List<Coupon> findSaleCoupon(String userId,String time) {
        return couponRepository.findSaleCoupon(userId,time);
    }

    public List<Coupon> findSaleExpireCoupon(String phone,String time) {
        return couponRepository.findSaleExpireCoupon(phone,time);
    }

    public List<Coupon> findMyCoupon(String phone,String time) {
        return couponRepository.findMyCoupon(phone,time);
    }


    public int completeMyFTask(UserTask userTask) {
        return userTaskRepository.update(userTask);
    }


    public List<String> completeMyTaskDetail(Integer userId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List ids = new ArrayList();
        ids.add(userId);
        return userTaskRepository.completeMyTaskDetail(ids,sdf.format(new Date()));
    }


    public void insertForward(Forward forward) {
        forwardRepository.save(forward);
    }


    public int grantCoupon(String phone,String couponCode){
        return couponRepository.grantCoupon(phone,couponCode);
    }

    public Coupon findByCode(String code) {
        return couponRepository.findByCode(code);
    }


}
